<?php


namespace app\api\controller;

use app\common\controller\Api;

class Shop extends Api
{
    protected $noNeedLogin = '';
    protected $noNeedRight = '*';

    /**
     * @var $model \app\common\model\Shop
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Shop();
    }

    /**
     * 店铺资料
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $user_id = input('param.user_id',0, 'intval');
        if (!$user_id){
            $this->error('参数错误');
        }
        if (!$shop = $this->model::getByUserId($user_id)) {
            $this->error('未找到该店铺');
        }
        $user = \app\common\model\User::get($user_id);
        $shop->userinfo = [
            'user_name' => $user->username,
            'nickname'  => $user->nickname,
            'avatar'    => $user->avatar,
            'gender'    => $user->gender,
            'introduction'=> $user->introduction
        ];
        $goods['on'] = $user->goods()->where(['onshelf_status'=>'1'])->count();
        $goods['off'] = $user->goods()->where(['onshelf_status'=>'0'])->count();
        $this->success('',['shop'=>$shop,'favorites_count'=>$user->favorites()->count(),'goods_count'=> $goods]);
    }

    /**
     * 修改店铺资料
     */
    public function profile()
    {
        $param = input('param.');
        $validate = new \app\api\validate\Shop();
        if (!$validate->check($param)){
            $this->error($validate->getError());
        }
        if (!$shop = $this->model::getByUserId($this->auth->id)) {
            $this->error('未找到您的店铺,请联系管理员');
        }
        if (isset($param['logo'])){
            $shop->logo = $param['logo'];
        }
        if (isset($param['background'])){
            $shop->background = $param['background'];
        }
        if (isset($param['name'])){
            $shop->name = $param['name'];
        }
        $shop->save();
        $this->success('修改成功');
    }
}